<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>MQTT管理</title>
    <base href="<%=request.getContextPath()%>/">
    <!-- 引入 EasyUI 的默认主题样式 -->
    <link rel="stylesheet" type="text/css" href="static/js/easyui/themes/bootstrap/easyui.css">
    <!-- 引入 EasyUI 的图标样式 -->
    <link rel="stylesheet" type="text/css" href="static/js/easyui/themes/icon.css">
    <!-- 引入自定义的公共CSS -->
    <link rel="stylesheet" type="text/css" href="static/css/common.css"/>
    <!-- 引入 EasyUI 默认的 jQuery（无需单独引入 jQuery） -->
    <script src="static/js/easyui/jquery.min.js"></script>
    <!-- 引入 EasyUI 的核心 JS 文件 -->
    <script src="static/js/easyui/jquery.easyui.min.js"></script>
    <!-- 引入 EasyUI 的中文语言包 -->
    <script src="static/js/easyui/locale/easyui-lang-zh_CN.js"></script>
    <!-- 引入自定义的公共脚本 -->
    <script src="static/js/owner/common.js"></script>
    <!-- 引入自定义的公共脚本 -->
    <script src="static/js/owner/dataGrid.js"></script>
    <script src="static/js/owner/moment.min.js"></script>
    <!-- daterangepicker 是一个日期范围选择插件，支持选择开始和结束日期 -->
    <link rel="stylesheet" href="static/css/daterangepicker.css">
    <!-- 引入 daterangepicker 的脚本文件 -->
    <script src="static/js/owner/daterangepicker.js"></script>
    <style>
        .mqtt-panel {
            margin: 10px;
        }
        .status-connected {
            color: green;
            font-weight: bold;
        }
        .status-disconnected {
            color: red;
            font-weight: bold;
        }
        .message-panel {
            margin-top: 20px;
        }
        .form-item {
            margin-bottom: 10px;
        }
        .form-item label {
            display: inline-block;
            width: 80px;
            text-align: right;
            margin-right: 10px;
        }
    </style>
</head>
<body class="easyui-layout">
<div data-options="region:'north',title:'MQTT连接状态',split:true,collapsible:true" style="height:auto;padding:10px;">
    <div class="mqtt-panel">
        <div>
            <span>连接状态:</span>
            <span class="${isConnected ? 'status-connected' : 'status-disconnected'}" id="connectionStatus">
                ${isConnected ? '已连接' : '未连接'}
            </span>
        </div>
        <div style="margin-top: 10px;">
            <a href="javascript:void(0)" class="easyui-linkbutton" onclick="reconnect()">重新连接</a>
        </div>
    </div>
</div>

<div data-options="region:'west',title:'发布消息',split:true,collapsible:true" style="width:400px;">
    <div class="mqtt-panel">
        <form id="publishForm">
            <div class="form-item">
                <label for="topic">主题:</label>
                <input class="easyui-textbox" id="topic" name="topic" style="width:250px;" required="true">
            </div>
            <div class="form-item">
                <label for="payload">消息内容:</label>
                <input class="easyui-textbox" id="payload" name="payload" data-options="multiline:true" style="width:250px;height:100px;" required="true">
            </div>
            <div class="form-item">
                <label for="format">消息格式:</label>
                <select class="easyui-combobox" id="format" name="format" style="width:250px;">
                    <option value="text">文本</option>
                    <option value="hex">十六进制</option>
                </select>
            </div>
            <div class="form-item">
                <label for="qos">QoS:</label>
                <select class="easyui-combobox" id="qos" name="qos" style="width:250px;">
                    <option value="0">0 - 至多一次</option>
                    <option value="1">1 - 至少一次</option>
                    <option value="2">2 - 确保只有一次</option>
                </select>
            </div>
            <div class="form-item">
                <label for="retained">保留消息:</label>
                <input class="easyui-switchbutton" id="retained" name="retained" data-options="onText:'是',offText:'否'">
            </div>
            <div class="form-item" style="text-align: center; margin-top: 20px;">
                <a href="javascript:void(0)" class="easyui-linkbutton" onclick="publishMessage()">发布消息</a>
            </div>
        </form>
    </div>
</div>

<div data-options="region:'center',title:'消息列表'">
    <div class="easyui-layout" data-options="fit:true">
        <div data-options="region:'north',split:true" style="height:120px;">
            <div class="mqtt-panel">
                <div class="form-item">
                    <label for="subscribeTopic">订阅主题:</label>
                    <input class="easyui-textbox" id="subscribeTopic" value="/a1T2mcqf2rP/869373061773850/user/update" style="width:250px;" required="true">
                    <select class="easyui-combobox" id="subscribeQos" style="width:100px;">
                        <option value="0">QoS 0</option>
                        <option value="1">QoS 1</option>
                        <option value="2">QoS 2</option>
                    </select>
                    <a href="javascript:void(0)" class="easyui-linkbutton" onclick="subscribeTopic()">订阅</a>
                </div>
                <div class="form-item">
                    <label>已订阅主题:</label>
                    <select class="easyui-combobox" id="subscribedTopics" style="width:250px;">
                        <c:forEach items="${subscribedTopics}" var="topic">
                            <option value="${topic}">${topic}</option>
                        </c:forEach>
                    </select>
                    <a href="javascript:void(0)" class="easyui-linkbutton" onclick="unsubscribeTopic()">取消订阅</a>
                    <a href="javascript:void(0)" class="easyui-linkbutton" onclick="clearMessages()">清空消息</a>
                </div>
            </div>
        </div>
        <div data-options="region:'center'">
            <table id="messageTable" class="easyui-datagrid"
                   data-options="singleSelect:true,fitColumns:true,toolbar:'#messageTb'">
                <thead>
                <tr>
                    <th data-options="field:'id',width:80,hidden:true">ID</th>
                    <th data-options="field:'topic',width:100">主题</th>
                    <th data-options="field:'payload',width:200">内容</th>
                    <th data-options="field:'format',width:60,align:'center',formatter:formatMessageFormat">格式</th>
                    <th data-options="field:'qos',width:50,align:'center'">QoS</th>
                    <th data-options="field:'retained',width:60,align:'center',formatter:formatRetained">保留</th>
                    <th data-options="field:'sendTime',width:150,formatter:formatTime">时间</th>
                    <th data-options="field:'remark',width:200">备注</th>
                </tr>
                </thead>
            </table>
            <div id="messageTb" style="padding:5px;">
                <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-reload" onclick="refreshMessages()">刷新</a>
                <span id="refreshStatus" style="margin-left: 5px; color: #888; display: none;">正在刷新...</span>
                <span style="margin-left: 20px;">
                        自动刷新：<input id="autoRefresh" class="easyui-switchbutton" data-options="onText:'开',offText:'关'">
                        间隔：<input id="refreshInterval" class="easyui-numberspinner" style="width:60px;"
                                    data-options="min:1,max:60,value:3,onChange:function(newValue,oldValue){
                                   if($('#autoRefresh').switchbutton('options').checked) {
                                       restartAutoRefresh();
                                   }
                               }"> 秒
                    </span>
                <span style="margin-left: 20px;">
                        按主题过滤：
                        <input id="filterTopic" class="easyui-combobox" style="width:200px;"
                               data-options="
                                   valueField: 'value',
                                   textField: 'text',
                                   editable: false,
                                   panelHeight: 'auto',
                                   onChange: function(newValue, oldValue) {
                                       refreshMessages();
                                   }
                               ">
                        <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-clear" onclick="clearFilter()">清除过滤</a>
                    </span>
            </div>
        </div>
    </div>
</div>

<script type="text/javascript">
    // 页面加载完成后执行
    $(function() {
        // 初始化消息表格
        refreshMessages();

        // 初始检查连接状态
        checkStatus();

        // 定时刷新连接状态（只保留状态检查，移除消息刷新）
        setInterval(function() {
            checkStatus();
        }, 5000);

        // 添加消息自动刷新开关
        $('#autoRefresh').switchbutton({
            checked: true,
            onChange: function(checked) {
                if (checked) {
                    $('#refreshInterval').textbox('enable');
                    startAutoRefresh();
                } else {
                    $('#refreshInterval').textbox('disable');
                    stopAutoRefresh();
                }
            }
        });

        // 初始化自动刷新
        startAutoRefresh();

        // 初始化过滤主题下拉框
        updateFilterTopics();
    });

    // 自动刷新定时器
    var autoRefreshTimer = null;
    // 标记是否正在刷新
    var isRefreshing = false;

    // 开始自动刷新
    function startAutoRefresh() {
        stopAutoRefresh(); // 先停止之前的定时器
        var interval = parseInt($('#refreshInterval').textbox('getValue')) || 3;
        autoRefreshTimer = setInterval(function() {
            if (!isRefreshing) { // 防止重复请求
                refreshMessages();
            }
        }, interval * 1000);
        console.log("已启动自动刷新，间隔: " + interval + "秒");
    }

    // 停止自动刷新
    function stopAutoRefresh() {
        if (autoRefreshTimer) {
            clearInterval(autoRefreshTimer);
            autoRefreshTimer = null;
            console.log("已停止自动刷新");
        }
    }

    // 检查连接状态
    function checkStatus() {
        $.ajax({
            url: 'mqtt/status',
            type: 'GET',
            dataType: 'json',
            success: function(result) {
                var status = result.connected ? '已连接' : '未连接';
                var className = result.connected ? 'status-connected' : 'status-disconnected';
                $('#connectionStatus').text(status).attr('class', className);
            }
        });
    }

    // 重新连接
    function reconnect() {
        $.ajax({
            url: 'mqtt/reconnect',
            type: 'POST',
            dataType: 'json',
            success: function(result) {
                if (result.success) {
                    $.messager.show({
                        title: '成功',
                        msg: result.message,
                        timeout: 2000
                    });
                    checkStatus();
                } else {
                    $.messager.alert('错误', result.message, 'error');
                }
            }
        });
    }

    // 发布消息
    function publishMessage() {
        var topic = $('#topic').textbox('getValue');
        var payload = $('#payload').textbox('getValue');
        var format = $('#format').combobox('getValue');
        var qos = $('#qos').combobox('getValue');
        var retained = $('#retained').switchbutton('options').checked;

        if (!topic || !payload) {
            $.messager.alert('警告', '主题和消息内容不能为空', 'warning');
            return;
        }

        // 验证十六进制格式
        if (format === 'hex' && !isValidHexString(payload)) {
            $.messager.alert('警告', '十六进制格式不正确，请输入有效的十六进制字符(0-9, A-F)', 'warning');
            return;
        }

        $.ajax({
            url: 'mqtt/publish',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({
                topic: topic,
                payload: payload,
                format: format,
                qos: qos,
                retained: retained
            }),
            dataType: 'json',
            success: function(result) {
                if (result.success) {
                    $.messager.show({
                        title: '成功',
                        msg: result.message,
                        timeout: 2000
                    });
                    // 清空消息内容
                    $('#payload').textbox('setValue', '');
                } else {
                    $.messager.alert('错误', result.message, 'error');
                }
            }
        });
    }

    // 订阅主题
    function subscribeTopic() {
        var topic = $('#subscribeTopic').textbox('getValue');
        var qos = $('#subscribeQos').combobox('getValue');

        if (!topic) {
            $.messager.alert('警告', '主题不能为空', 'warning');
            return;
        }

        $.ajax({
            url: 'mqtt/subscribe',
            type: 'POST',
            data: {
                topic: topic,
                qos: qos
            },
            dataType: 'json',
            success: function(result) {
                if (result.success) {
                    $.messager.show({
                        title: '成功',
                        msg: result.message,
                        timeout: 2000
                    });
                    // 添加到已订阅主题列表
                    var exists = false;
                    var topics = $('#subscribedTopics').combobox('getData');
                    for (var i = 0; i < topics.length; i++) {
                        if (topics[i].value === topic) {
                            exists = true;
                            break;
                        }
                    }
                    if (!exists) {
                        $('#subscribedTopics').combobox('appendItem', {
                            value: topic,
                            text: topic
                        });
                    }
                    // 清空输入框
                    $('#subscribeTopic').textbox('setValue', '');

                    // 立即刷新消息列表以显示新订阅主题的消息
                    refreshMessages();

                    // 更新过滤主题下拉框
                    updateFilterTopics();
                } else {
                    $.messager.alert('错误', result.message, 'error');
                }
            }
        });
    }

    // 取消订阅
    function unsubscribeTopic() {
        var topic = $('#subscribedTopics').combobox('getValue');

        if (!topic) {
            $.messager.alert('警告', '请选择要取消订阅的主题', 'warning');
            return;
        }

        $.ajax({
            url: 'mqtt/unsubscribe',
            type: 'POST',
            data: {
                topic: topic
            },
            dataType: 'json',
            success: function(result) {
                if (result.success) {
                    $.messager.show({
                        title: '成功',
                        msg: result.message,
                        timeout: 2000
                    });
                    // 从已订阅主题列表中移除
                    var topics = $('#subscribedTopics').combobox('getData');
                    for (var i = 0; i < topics.length; i++) {
                        if (topics[i].value === topic) {
                            $('#subscribedTopics').combobox('removeItem', topic);
                            break;
                        }
                    }

                    // 更新过滤主题下拉框
                    updateFilterTopics();

                    // 如果当前过滤的是被取消订阅的主题，则清除过滤
                    if ($('#filterTopic').combobox('getValue') === topic) {
                        $('#filterTopic').combobox('clear');
                    }

                    // 刷新消息列表
                    refreshMessages();
                } else {
                    $.messager.alert('错误', result.message, 'error');
                }
            }
        });
    }

    // 刷新消息列表
    function refreshMessages() {
        var filterTopic = $('#filterTopic').combobox('getValue');

        // 设置刷新状态
        isRefreshing = true;
        $('#refreshStatus').show(); // 显示刷新状态

        $.ajax({
            url: 'mqtt/messages',
            type: 'GET',
            data: {
                topic: filterTopic
            },
            dataType: 'json',
            success: function(result) {
                if (result.success) {
                    $('#messageTable').datagrid('loadData', result.data);
                }
                isRefreshing = false; // 重置刷新状态
                $('#refreshStatus').hide(); // 隐藏刷新状态
            },
            error: function() {
                isRefreshing = false; // 出错时也要重置刷新状态
                $('#refreshStatus').hide(); // 隐藏刷新状态
            }
        });
    }

    // 清空消息
    function clearMessages() {
        var topic = $('#subscribedTopics').combobox('getValue');

        $.ajax({
            url: 'mqtt/clear',
            type: 'POST',
            data: {
                topic: topic
            },
            dataType: 'json',
            success: function(result) {
                if (result.success) {
                    $.messager.show({
                        title: '成功',
                        msg: result.message,
                        timeout: 2000
                    });
                    refreshMessages();
                } else {
                    $.messager.alert('错误', result.message, 'error');
                }
            }
        });
    }

    // 格式化保留消息显示
    function formatRetained(val) {
        return val ? '是' : '否';
    }

    // 格式化消息格式显示
    function formatMessageFormat(val) {
        if (val === 'hex') {
            return '<span style="color:blue;">十六进制</span>';
        } else {
            return '文本';
        }
    }

    // 验证十六进制字符串
    function isValidHexString(str) {
        // 移除所有空格
        str = str.replace(/\s/g, '');
        // 检查是否为有效的十六进制字符串
        return /^[0-9A-Fa-f]*$/.test(str);
    }

    // 格式化时间显示
    function formatTime(val) {
        if (!val) return '';
        var date = new Date(val);
        return date.getFullYear() + '-' +
            padZero(date.getMonth() + 1) + '-' +
            padZero(date.getDate()) + ' ' +
            padZero(date.getHours()) + ':' +
            padZero(date.getMinutes()) + ':' +
            padZero(date.getSeconds());
    }

    // 数字补零
    function padZero(num) {
        return num < 10 ? '0' + num : num;
    }

    // 清除过滤
    function clearFilter() {
        $('#filterTopic').combobox('clear');
        refreshMessages();
    }

    // 更新过滤主题下拉框
    function updateFilterTopics() {
        var topics = $('#subscribedTopics').combobox('getData');
        var filterTopics = [{ value: '', text: '全部主题' }];

        for (var i = 0; i < topics.length; i++) {
            filterTopics.push({
                value: topics[i].value,
                text: topics[i].text
            });
        }

        $('#filterTopic').combobox('loadData', filterTopics);
    }

    // 重新启动自动刷新（用于间隔变更时）
    function restartAutoRefresh() {
        if (autoRefreshTimer) {
            stopAutoRefresh();
            startAutoRefresh();
        }
    }
</script>
</body>
</html>
